﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using XfTechOAWeb.Dtos;
using XfTechOAWeb.Dtos.Syslog;
using XfTechOAWeb.Infrastructure.Enums;
using XfTechOAWeb.Infrastructure.Extensions;
using XfTechOAWeb.IService;

using NPOI.SS.UserModel; //引用命名空间
using Microsoft.AspNetCore.Hosting;
using System.IO;
using System.Net;
using System.Web;
using System.Net.Http.Headers;
using Microsoft.AspNetCore.Authorization;
using NPOI.SS.Formula.Functions;

namespace XfTechOAWeb.ApiServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SysLogsController : ControllerBase
    {
        private readonly IOperationLogService _operationService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="operationService"></param>
        public SysLogsController(IOperationLogService operationService)
        {
            _operationService = operationService;
        }

        /// <summary>
        /// 日志显示
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetLogs([FromQuery]LogsPageRequestDto input)
        {
            var data = _operationService.GetPageList(input);

            return Ok(new ResponseModel<object>
            {
                Code = (int)ResponseCode.Success,
                Msg = ResponseCode.Success.GetDescription(),
                Data = data
            });
        }

        /// <summary>
        /// 导出日志
        /// </summary>
        /// <param name="input"></param>
        /// <param name="hostEnvironment"></param>
        /// <returns></returns>
        [HttpGet("Export")]
        public IActionResult Export([FromQuery]LogsPageRequestDto input, [FromServices] IWebHostEnvironment hostEnvironment)
        {
            //第一步，根据条件去查数据库，查到符合条件的日志数据
            var data = _operationService.GetList(input);

            //读取Files/日志导出模板.xlsx，来创建一个Workbook对象
            string templatePath = hostEnvironment.WebRootPath + @"/Files/日志导出模板.xlsx";
            
            //创建一个工作簿对象
            IWorkbook wb = WorkbookFactory.Create(templatePath);

            //获取工作簿中的第一个Sheet对象
            ISheet sheet = wb.GetSheetAt(0);

            //先把标题加进去
            IRow header = sheet.CreateRow(0);
            for (int j = 0; j < 7; j++)
            {
                header.CreateCell(j);  //在行里面创建7个单元格
            }
            header.Cells[0].SetCellValue("序号");
            //略了

            //创建行，并给单元格赋值（填充内容）
            for (int i = 0; i < data.Count; i++)
            {
                IRow row = sheet.CreateRow(i + 1);  //创建了一行
                                                    //创建单元格
                for (int j = 0; j < 7; j++)
                {
                    row.CreateCell(j);  //在行里面创建7个单元格
                }
                //导数据
                row.Cells[0].SetCellValue(i);
                row.Cells[1].SetCellValue(data[i].OperatorName);
                row.Cells[2].SetCellValue(data[i].CreateTimes);
                row.Cells[3].SetCellValue(data[i].Module);
                row.Cells[4].SetCellValue(data[i].Content);
                row.Cells[5].SetCellValue(data[i].Classify);
                row.Cells[6].SetCellValue(data[i].Whether);

            }

            //返回给用户去下载这个文件
            //3. 返回文件（下载）(把以上内存中的信息，导出到文件）
            //MemoryStream 内存流
            MemoryStream stream = new MemoryStream();
            wb.Write(stream, true);

            stream.Flush();      //刷新缓冲区
            stream.Position = 0; //文件流指针重置为0

            string newFileName = $"导出数据{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";

            //向客户端暴露响应头
            Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

            return File(stream.ToArray(), "application/octet-stream", newFileName);
        }


        /// <summary>
        /// 下载文件（最简单的形式）
        /// </summary>
        /// <param name="hostEnvironment"></param>
        /// <returns></returns>
        [HttpGet("DownloadTemplate")]
        [AllowAnonymous] //允许匿名下载
        public IActionResult Download([FromServices]IWebHostEnvironment hostEnvironment)
        {
            string path = hostEnvironment.WebRootPath + @"/Files/1.png";
            
            //通过文件流操作，打开文件流
            FileStream fileStream = System.IO.File.OpenRead(path);

            return File(fileStream, "image/jpeg", "123.png");
        }


    }
}
